<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isMobile ? '' : '注册'"
    :width="dialogWidth"
    @close="handleClose"
    :fullscreen="isMobile"
    :top="isMobile ? '0vh' : '15vh'"
    :class="{ 'mobile-dialog': isMobile }"
  >
    <el-form
      ref="registerFormRef"
      :model="registerForm"
      :rules="rules"
      @submit.prevent="submitRegister"
      label-position="top"
      :label-width="formLabelWidth"
      class="register-form"
    >
      <h2 v-if="isMobile" class="mobile-title">注册</h2>
      <el-form-item label="用户名" prop="username">
        <el-input v-model="registerForm.username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="registerForm.password" type="password" placeholder="请输入密码"></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input
          v-model="registerForm.confirmPassword"
          type="password"
          placeholder="请再次输入密码"
        ></el-input>
      </el-form-item>
      <el-form-item v-if="isMobile">
        <el-button type="primary" @click="submitRegister" class="mobile-submit-btn">注册</el-button>
      </el-form-item>
    </el-form>
    <template #footer>
      <span v-if="!isMobile" class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitRegister">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, computed, defineProps, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
import { useWindowSize } from '@vueuse/core'
import { register } from '@/api/users' // 导入注册 API

// 定义组件的 props
const props = defineProps({
  visible: Boolean, // 控制对话框是否可见
})

// 定义组件的 emits
const emit = defineEmits(['close'])

// 响应式变量
const dialogVisible = ref(props.visible) // 控制对话框的可见性
const registerFormRef = ref(null) // 表单引用，用于表单验证
const registerForm = ref({
  username: '',
  password: '',
  confirmPassword: '',
})

// 使用 vueuse 的 useWindowSize 来获取窗口大小
const { width } = useWindowSize()

// 计算属性
const isMobile = computed(() => width.value < 768) // 判断是否为移动设备
const dialogWidth = computed(() => (isMobile.value ? '100%' : '30%')) // 根据设备类型设置对话框宽度
const formLabelWidth = computed(() => (isMobile.value ? 'auto' : '120px')) // 设置表单标签宽度

// 密码验证函数
const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (registerForm.value.confirmPassword !== '') {
      registerFormRef.value.validateField('confirmPassword')
    }
    callback()
  }
}

// 确认密码验证函数
const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.value.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, validator: validatePass, trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, validator: validatePass2, trigger: 'blur' },
  ],
}

// 监听 props.visible 的变化，同步更新 dialogVisible
watch(
  () => props.visible,
  (newValue) => {
    dialogVisible.value = newValue
  },
)

// 处理对话框关闭
const handleClose = () => {
  registerFormRef.value.resetFields() // 重置表单
  emit('close') // 触发关闭事件
}

// 提交注册
const submitRegister = () => {
  registerFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await register({
          username: registerForm.value.username,
          password: registerForm.value.password,
        })
        console.log('注册响应:', response)
        if (response.code === 0) {
          ElMessage.success('注册成功')
          handleClose()
        } else {
          ElMessage.error(response.message || '注册失败')
        }
      } catch (error) {
        console.error('注册错误:', error)
        ElMessage.error(error.message || '注册失败')
      }
    } else {
      console.log('表单验证失败')
      return false
    }
  })
}
</script>

<style scoped>
.el-dialog {
  max-width: 100%;
}

.register-form {
  max-width: 300px;
  margin: 0 auto;
}

@media (max-width: 768px) {
  .mobile-dialog {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background-color: rgba(255, 255, 255, 0.9);
  }

  .mobile-dialog :deep(.el-dialog__header) {
    padding: 0;
  }

  .mobile-dialog :deep(.el-dialog__body) {
    padding: 20px;
  }

  .mobile-title {
    text-align: center;
    font-size: 24px;
    margin-bottom: 20px;
  }

  .register-form {
    width: 100%;
    max-width: none;
  }

  .register-form :deep(.el-form-item__label) {
    padding: 0;
  }

  .register-form :deep(.el-input__inner) {
    border-radius: 20px;
  }

  .mobile-submit-btn {
    width: 100%;
    border-radius: 20px;
    margin-top: 20px;
  }

  .dialog-footer {
    display: flex;
    justify-content: space-between;
    width: 100%;
  }

  .dialog-footer .el-button {
    flex: 1;
  }
}
</style>